import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:io';
import '../models/essay_material.dart';
import '../repositories/essay_material_repository.dart';
import '../widgets/image_preview_widget.dart';

class EssayMaterialDetailScreen extends StatefulWidget {
  final int materialId;
  final int? fromTabIndex;
  
  const EssayMaterialDetailScreen({
    super.key,
    required this.materialId,
    this.fromTabIndex,
  });

  @override
  State<EssayMaterialDetailScreen> createState() => _EssayMaterialDetailScreenState();
}

class _EssayMaterialDetailScreenState extends State<EssayMaterialDetailScreen> {
  bool _isLoading = true;
  EssayMaterial? _material;
  final _essayMaterialRepository = EssayMaterialRepository();
  
  @override
  void initState() {
    super.initState();
    _loadMaterialData();
  }
  
  Future<void> _loadMaterialData() async {
    setState(() => _isLoading = true);
    
    try {
      // 从数据库加载素材数据
      final material = await _essayMaterialRepository.getEssayMaterialById(widget.materialId);
      
      setState(() {
        _material = material;
        _isLoading = false;
      });
    } catch (e) {
      print('加载素材详情错误: $e'); // 添加错误日志
      setState(() => _isLoading = false);
      _showErrorSnackBar('加载素材数据失败: $e');
    }
  }
  
  Future<void> _copyContent() async {
    if (_material == null) return;
    
    await Clipboard.setData(ClipboardData(text: _material!.content));
    _showSuccessSnackBar('内容已复制到剪贴板');
  }
  
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }
  
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_isLoading ? '素材详情' : _material?.title ?? '素材详情'),
        centerTitle: true,
        actions: [
          if (!_isLoading && _material != null)
            IconButton(
              icon: const Icon(Icons.copy),
              onPressed: _copyContent,
              tooltip: '复制内容',
            ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _material == null
              ? const Center(child: Text('素材不存在或已被删除'))
              : SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 标题和分类
                      Text(
                        _material!.title,
                        style: Theme.of(context).textTheme.headlineSmall,
                      ),
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          Chip(
                            label: Text(_material!.category),
                            backgroundColor: Colors.blue.shade100,
                          ),
                          const SizedBox(width: 8),
                          Text(
                            '创建于: ${_formatDate(DateTime.fromMillisecondsSinceEpoch(_material!.createdAt))}',
                            style: TextStyle(color: Colors.grey[600], fontSize: 14),
                          ),
                        ],
                      ),
                      
                      // 显示图片（如果有）
                      if (_material!.imageUrl != null && _material!.imageUrl!.isNotEmpty) ...[  
                        const SizedBox(height: 16),
                        ClipRRect(
                          borderRadius: BorderRadius.circular(8),
                          child: ImagePreviewWidget(
                            imageUrl: _material!.imageUrl!,
                            width: double.infinity,
                            height: 200,
                            fit: BoxFit.contain,
                            showPath: false,
                          ),
                        ),
                      ],
                      
                      const Divider(height: 32),
                      
                      // 内容
                      Text(
                        _material!.content,
                        style: const TextStyle(fontSize: 16, height: 1.6),
                      ),
                      
                      // 显示标签和来源（如果有）
                      if (_material!.tags.isNotEmpty) ...[  
                        const SizedBox(height: 24),
                        const Text('标签:', style: TextStyle(fontWeight: FontWeight.bold)),
                        const SizedBox(height: 4),
                        Wrap(
                          spacing: 8,
                          children: _material!.tags.split(',').map((tag) => 
                            Chip(
                              label: Text(tag.trim()),
                              backgroundColor: Colors.green.shade100,
                            )
                          ).toList(),
                        ),
                      ],
                      
                      if (_material!.source.isNotEmpty) ...[  
                        const SizedBox(height: 16),
                        const Text('来源:', style: TextStyle(fontWeight: FontWeight.bold)),
                        const SizedBox(height: 4),
                        Text(_material!.source),
                      ],
                    ],
                  ),
                ),
      floatingActionButton: !_isLoading && _material != null
          ? FloatingActionButton(
              onPressed: _copyContent,
              child: const Icon(Icons.copy),
              tooltip: '复制内容',
            )
          : null,
    );
  }
  
  String _formatDate(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}';
  }
}